package com.studentstreet;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.Display;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.GridView;
import android.widget.Toast;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.studentstreet.adapter.GridViewAdapter;
import com.studentstreet.component.AbstractCommonActivity;
import com.studentstreet.component.LoadStateView;
import com.studentstreet.component.LwtAlertDialog;
import com.studentstreet.component.LwtAlertDialog.Builder;
import com.studentstreet.entities.SellerEntity;
import com.studentstreet.tools.HttpHelper;
import com.studentstreet.tools.PreferenceTools;
import com.studentstreet.tools.SortById;
import com.studentstreet.tools.SortByRank;
import com.studentstreet.tools.Util;
import com.studentstreet.tools.dbhelper.SellerDBHelper;

/**
 * @author likebamboo
 * 
 */
public class SellerActivity extends AbstractCommonActivity {

	// 2013-05-29加入地理位置应用
	/** 定位Client */
	public LocationClient mLocClient = null;
	/** 百度位置监听器 */
	private BDLocationListener mLocListener = new MyLocListener();

	// Seller所采用的GridView布局
	private GridView mGridView = null;
	// 适配器
	GridViewAdapter mGridViewAdapter = null;
	// Seller Json 数据
	private String sellerJson = "";

	private LoadStateView loadStateView;
	// 刷新列表
	private static final int REFRESH_LIST = 0x10001;
	// 列表为空
	private static final int LIST_IS_EMPTY = 0x10005;
	// 获得地理位置OK
	private static final int GET_LOC = 0x10010;
	// 商家列表
	List<SellerEntity> sellerList = null;
	// 排序按钮
	private Button sortBt = null;
	// 排序方式
	private boolean sortByRank = false;

	// 所选择的项
	private static int CHECK_ITEM = 0;

	// 距离
	private double distance = 0D;

	private PreferenceTools prefTools = new PreferenceTools(this);

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		// 设置本Activity 无title
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.seller);
		// 将当前Activity压入堆栈中
		MyApp.getInstance().addActivity(this);

		// OEM++
		// 声明LocationClient类
		mLocClient = new LocationClient(getApplicationContext());
		LocationClientOption option = new LocationClientOption();
		option = getOption();
		mLocClient.setLocOption(option);
		// 注册监听函数
		mLocClient.registerLocationListener(mLocListener);
		if (mLocClient != null) {
			if (!mLocClient.isStarted()) {
				mLocClient.start();
			}
			mLocClient.requestLocation();
		} else {
			System.out.println("locClient is null or not started");
		}
		// OEM--

		// 获得屏幕的大小
		Display display = getWindowManager().getDefaultDisplay();
		int width = display.getWidth();
		int height = display.getHeight();

		mGridView = (GridView) findViewById(R.id.seller_gridView);
		// 设置GridView中元素的垂直间距
		mGridView.setVerticalSpacing((int) (width * 0.02));
		// 设置GridView中元素的水平间距
		mGridView.setHorizontalSpacing((int) (width * 0.02));
		loadStateView = (LoadStateView) findViewById(R.id.downloadStatusBox);
		// 创建GridView的适配器
		mGridViewAdapter = new GridViewAdapter(this, mGridView);
		// 设置适配器
		mGridView.setAdapter(mGridViewAdapter);
		// 加载商家类别
		loadSeller();
		// 为GridView添加单击事件
		mGridView.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View v,
					int position, long id) {
				Intent intent = new Intent(SellerActivity.this,
						GoodsActivity.class);
				intent.putExtra("seller_id", sellerList.get(position).getId());
				intent.putExtra("seller_name", sellerList.get(position)
						.getName());
				startActivity(intent);
			}

		});

		// 设置 "重新加载" 监听器
		loadStateView.setOnReloadClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				loadSeller();
			}
		});

		// 初始化排序按钮
		sortBt = (Button) findViewById(R.id.seller_sortBt);
		sortBt.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				showSortDialog();
			}
		});
	}

	/**
	 * OEM++ liwt 2013-05-29 设置LocationClient的首选项信息。
	 * 
	 * @return Option信息
	 */
	private LocationClientOption getOption() {
		LocationClientOption option = new LocationClientOption();
		// 不打开gps（gps定位比较慢，而且不能在室内用）
		option.setOpenGps(false);
		// 返回的定位结果包含地址信息
		option.setAddrType("all");
		// 返回的定位结果是百度经纬度,默认值gcj02
		option.setCoorType("bd09ll");
		// 设置发起定位请求的间隔时间为30000ms
		option.setScanSpan(30000);
		// 禁止启用缓存定位
		option.disableCache(true);
		// 最多返回POI个数
		// option.setPoiNumber(5);
		// poi查询距离
		// option.setPoiDistance(1000);
		// 是否需要POI的电话和地址等详细信息
		// option.setPoiExtraInfo(true);
		return option;
	}

	// 加载商家列表
	private void loadSeller() {
		// 开始加载，此时会显示ProgressBar，隐藏 “重新加载” 按钮
		loadStateView.startLoad();
		new Thread(new Runnable() {
			@Override
			public void run() {
				// 使用apache HTTP客户端实现
				String urlStr = Util.BASE_URL + "/servlet/SellerServlet";
				// 创建网络连接工具对象
				HttpHelper helper = new HttpHelper(urlStr);
				// 添加参数
				// 请求标记
				if (CHECK_ITEM == 0) {
					helper.addParam("action", "getAllSeller");
				} else {
					helper.addParam("action", "getLocSeller");
					helper.addParam("lon", prefTools.getLon() + "");
					helper.addParam("lat", prefTools.getLat() + "");
					helper.addParam("distance", distance+"");
				}

				// 获得服务器返回的数据
				sellerJson = helper.getResponse();
				// 如果返回的数据不为空，修改登录标志为 true
				if ("".equals(sellerJson)) {
					sendMessage(LIST_IS_EMPTY);
					return;
				}
				// 将Json数据转化并填充到GridView中
				loadDate();
				// 通知GridView的适配器，数据有更新
				sendMessage(REFRESH_LIST);
			}
		}).start();
	}

	public void loadDate() {
		mGridViewAdapter.clean();
		if (sellerJson.equals("")) {
			return;// 应从本地数据库读，暂时不实现；
		}
		// 间数据保存到本地
		SellerDBHelper dbHelper = new SellerDBHelper(this);
		dbHelper.saveToDB(sellerJson);
		// 填充列表并显示
		Type listType = new TypeToken<ArrayList<SellerEntity>>() {
		}.getType();
		Gson gson = new Gson();
		sellerList = gson.fromJson(sellerJson, listType);
		Collections.sort(sellerList, new SortByRank());
		sortByRank = true;
		for (SellerEntity seller : sellerList) {
			// 把商品图片路径补充完整
			seller.setLogoURL(Util.BASE_SELLERS_LOGO_URL + seller.getLogoURL());
			mGridViewAdapter.addSeller(seller);
		}
	}

	@Override
	protected void handleOtherMessage(int flag) {
		switch (flag) {
		case REFRESH_LIST:
			// 更新mGridViewAdapter
			mGridViewAdapter.notifyDataSetChanged();
			// 让ProgressBar消失
			loadStateView.stopLoad();
			// 如果列表为空，显示提示信息
			if (mGridViewAdapter.getCount() == 0) {
				// loadStateView.showEmpty();
			}
			break;
		case LIST_IS_EMPTY:
			// 让ProgressBar消失
			loadStateView.stopLoad();
			loadStateView.showError();
			break;
		case GET_LOC:
			// 地理位置OK
			sortBt.setVisibility(View.VISIBLE);
		default:
			break;
		}

	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			MyApp.getInstance().exit(this);
		}
		return super.onKeyDown(keyCode, event);
	}

	/**
	 * 位置变化的监听器
	 * 
	 * @author likebamboo
	 * 
	 */
	public class MyLocListener implements BDLocationListener {

		@Override
		public void onReceiveLocation(BDLocation location) {
			if (location == null || location.getProvince() == null
					|| location.getCity() == null
					|| location.getCityCode() == null) {
				return;
			}
			String msg = "---------获得的地址信息--------";
			msg += "\n经度：" + location.getLongitude();
			msg += "\n纬度：" + location.getLatitude();
			msg += "\n地址：" + location.getAddrStr();
			msg += "\n省份：" + location.getProvince();
			msg += "\n城市：" + location.getCity() + "," + location.getCityCode();
			System.out.println(msg);
			// 保存地址信息
			if (saveLocInfo((float) location.getLongitude(),
					(float) location.getLatitude(), location.getAddrStr())) {
				sendMessage(GET_LOC);
			}
		}

		@Override
		public void onReceivePoi(BDLocation arg0) {
		}
	}

	// 显示排序列表
	private void showSortDialog() {
		final Builder builder = new LwtAlertDialog.Builder(this);
		builder.setTitle("您当前的位置是：" + prefTools.getLoc())
				.setIcon(android.R.drawable.ic_dialog_info)
				.setSingleChoiceItems(new String[] { "所有商家", "附近200米","附近500米","附近1000米","附近2000米","附近5000米" },
						CHECK_ITEM, new LwtAlertDialog.OnClickListener() {
							@Override
							public void onClick(DialogInterface dialog,
									int which) {
								switch (which) {
								case 0:// 全部
									if (CHECK_ITEM == 0) {// 如果当前的排序正是所选的，则什么都不做
										dialog.dismiss();
										return;
									}
									break;
								case 1:// 附近200米
									if (CHECK_ITEM == 1) {// 如果当前的排序正是所选的，则什么都不做
										dialog.dismiss();
										return;
									}
									distance = 200D;
									break;
								case 2:// 附近500米
									if (CHECK_ITEM ==2) {// 如果当前的排序正是所选的，则什么都不做
										dialog.dismiss();
										return;
									}
									distance = 500D;
									break;
								case 3:// 附近1000米
									if (CHECK_ITEM == 3) {// 如果当前的排序正是所选的，则什么都不做
										dialog.dismiss();
										return;
									}
									distance = 1000D;
									break;
								case 4:// 附近2000米
									if (CHECK_ITEM == 4) {// 如果当前的排序正是所选的，则什么都不做
										dialog.dismiss();
										return;
									}
									distance = 2000D;
									break;
								case 5:// 附近5000米
									if (CHECK_ITEM == 5) {// 如果当前的排序正是所选的，则什么都不做
										dialog.dismiss();
										return;
									}
									distance = 5000D;
									break;

								default:
									break;
								}
								CHECK_ITEM = which;
								dialog.dismiss();
								loadSeller();
							}
						});
		Dialog dialog = builder.create();
		// 显示对话框
		dialog.show();
	}

	// 保存地址信息
	private boolean saveLocInfo(float lon, float lat, String loc) {
		return prefTools.saveLoc(lon, lat, loc);
	}

	@Override
	protected void onPause() {
		super.onPause();
		mLocClient.unRegisterLocationListener(mLocListener);
		mLocClient.stop();
	}

}